package com.abe.mvp.view.activity;

import java.util.ArrayList;
import java.util.List;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.abe.config.Constants;
import com.abe.config.SettingParam;
import com.abe.mvp.contact.SocketContact;
import com.abe.mvp.model.bean.CardMenuBean;
import com.abe.mvp.model.bean.SettingBean;
import com.abe.mvp.presenter.SocketPresenterImp;
import com.abe.mvp.view.activity.base.BaseActivity;
import com.abe.mvp.view.adapter.CardMenuAdapter;
import com.abe.threadmill.R;
import com.abe.utils.NormalUtils;
import com.abe.utils.SPUtils;
import com.abe.view.CircleImageView;
import com.squareup.picasso.Picasso;

/**
 * @author yaopeng
 * */
@SuppressLint("ResourceAsColor")
@ContentView(R.layout.activity_tm_main_menu)
public class MainMenuActivity extends BaseActivity implements
		OnItemClickListener, SocketContact.View {

	private SocketContact.Presenter socketPresenter;

	@ViewInject(R.id.show_exercise_button_back)
	private LinearLayout show_exercise_button_back;
	@ViewInject(R.id.show_exercise_logo)
	private ImageView show_exercise_logo;

	@ViewInject(R.id.tabmenu_layout)
	private ImageView tabmenu_layout;

	@ViewInject(R.id.menu_text_user_name)
	private TextView menu_text_user_name;
	@ViewInject(R.id.menu_image_user_header)
	private CircleImageView menu_image_user_header;

	@ViewInject(R.id.tabmenu_list_h_menu)
	private GridView tabmenu_list_h_menu;
	private List<CardMenuBean> cardMenuBeans;
	private CardMenuAdapter cardMenuAdapter;

	@ViewInject(R.id.tabmenu_list_h_menu_target)
	private GridView tabmenu_list_h_menu_target;
	private List<CardMenuBean> targetCardMenuBeans;
	private CardMenuAdapter targetCardMenuAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initBackground();
		initData();
	}

	@Override
	protected void onResume() {
		super.onResume();
		initView();
	}

	private void initData() {
		socketPresenter = new SocketPresenterImp(this);
		SettingBean settingBean = SettingParam.getSettingBean();
		socketPresenter.openSocket(settingBean.getSocketIp(),
				settingBean.getSocketPort());
		show_exercise_button_back.setVisibility(View.VISIBLE);
		show_exercise_logo.setVisibility(View.VISIBLE);
		menu_text_user_name.setText(current_user.getUser().getUserName());
	}

	private void initView() {

		String image = current_user.getUser().getHeadimgurl();
		if (image.equals("")) {
			Picasso.with(getApplicationContext()).load(R.drawable.app_logo)
					.into(menu_image_user_header);
		} else {
			Picasso.with(getApplicationContext()).load(image)
					.into(menu_image_user_header);
		}
		/** 根据用户初始化本次登录累计运动统计 */
		/*********************** 目标 ************************/
		targetCardMenuBeans = new ArrayList<CardMenuBean>();
		int background[] = { R.drawable.time_bg, R.drawable.cs_bg,
				R.drawable.kll_bg };
		int targetDrawable[] = { R.drawable.icon_time, R.drawable.icon_cs,
				R.drawable.icon_kll };
		int[] names = { R.string.common_time, R.string.common_distance,
				R.string.common_calorie };
		for (int i = 0; i < 3; i++) {
			CardMenuBean bean = new CardMenuBean();
			bean.setBackground(background[i]);
			bean.setName(NormalUtils.getString(names[i]));
			bean.setDrawable(targetDrawable[i]);
			bean.setType(Integer.class);
			targetCardMenuBeans.add(bean);
		}
		targetCardMenuAdapter = new CardMenuAdapter(this, targetCardMenuBeans,
				scale, CardMenuAdapter.FLAG_TARGET_1);
		tabmenu_list_h_menu_target.setAdapter(targetCardMenuAdapter);
		tabmenu_list_h_menu_target.setOnItemClickListener(this);
		/************************** 其他 **************************/
		cardMenuBeans = new ArrayList<CardMenuBean>();
		int drawable[] = { R.drawable.home_yy, R.drawable.home_report,
				R.drawable.home_tnlljc, R.drawable.home_cx };
		int[] qtnames = { R.string.common_language, R.string.common_report,
				R.string.common_manual_mode, R.string.common_choose_mode };
		for (int i = 0; i < 4; i++) {
			CardMenuBean bean = new CardMenuBean();
			bean.setName(NormalUtils.getString(qtnames[i]));
			bean.setDrawable(drawable[i]);
			bean.setType(Integer.class);
			cardMenuBeans.add(bean);
		}
		cardMenuAdapter = new CardMenuAdapter(this, cardMenuBeans, scale,
				CardMenuAdapter.FLAG_QT_1);
		tabmenu_list_h_menu.setAdapter(cardMenuAdapter);
		tabmenu_list_h_menu.setOnItemClickListener(this);
	}

	@Event(value = R.id.show_exercise_button_back, type = View.OnClickListener.class)
	private void back(View view) {
		String exercise_language = (String) SPUtils.get(
				getApplicationContext(), SettingParam.SP_LANGUAGE_KEY,
				SettingParam.LANGUAGE_KEY_CN);
		String app_language = SettingParam.getSettingBean().getLanguage();
		if (exercise_language.equals(app_language)) {
			NormalUtils.setAppLanguage();
		}
		Intent intent = new Intent();
		intent.putExtra("extra", Constants.ExitApp);
		setResult(RESULT_OK, intent);
		back();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		if (parent.equals(tabmenu_list_h_menu_target)) {
			/** 目标 */
			gotoExerciseMain(MainActivity.SELECT_TARGET, pos);
		} else if (parent.equals(tabmenu_list_h_menu)) {
			switch (pos) {
			case 3:
				/** 模式选择 */
				gotoExerciseMain(MainActivity.SELECT_MOTOR_PATTERN, 0);
				break;
			case 2:
				/** 手动 */
				gotoExerciseMain(MainActivity.SELECT_TRAIL, 0);
				break;
			case 1:
				/** 报告 */
				gotoActivity(ExerciseReportActivity.class);
				break;
			case 0:
				/** 语言 */
				switchLanguage();
				break;
			}
		}
	}

	private void switchLanguage() {
		String language = (String) SPUtils.get(getApplicationContext(),
				SettingParam.SP_LANGUAGE_KEY, SettingParam.LANGUAGE_KEY_CN);
		if (language.equals(SettingParam.LANGUAGE_KEY_CN)) {
			SPUtils.put(getApplicationContext(), SettingParam.SP_LANGUAGE_KEY,
					SettingParam.LANGUAGE_KEY_EN);
		} else {
			SPUtils.put(getApplicationContext(), SettingParam.SP_LANGUAGE_KEY,
					SettingParam.LANGUAGE_KEY_CN);
		}
		language = (String) SPUtils.get(getApplicationContext(),
				SettingParam.SP_LANGUAGE_KEY, SettingParam.LANGUAGE_KEY_CN);
		/** 更新语言后，destroy当前页面，重新绘制 */
		NormalUtils.setExerciseLanguage();
		Intent intent = new Intent();
		intent.putExtra("extra", Constants.SettingLanguage);
		setResult(RESULT_OK, intent);
		back();
	}

	private void gotoExerciseMain(int tab, int pos) {
		Bundle bundle = new Bundle();
		bundle.putInt("pos", pos);
		bundle.putInt("tab", tab);
		gotoActivityForResult(MainActivity.class, bundle, 0);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (data != null) {
				gotoActivityForResult(ExerciseDataActivity.class,
						data.getExtras(), 0);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void initBackground() {
		/** 菜单页背景 */
		Picasso.with(this).load(R.drawable.run_image_bg_05).centerCrop()
				.placeholder(R.drawable.app_theme_bg).resize(1280, 720)
				.into(tabmenu_layout);
	}

	@Override
	public void onSocketConnectSuccess() {
		localSendEmptyMessage(socketLogin);
	}

	@Override
	public void onSocketCloseSuccess() {

	}

	@Override
	public void onSocketSendDataSuccess() {
		localSendEmptyMessage(socketClose);
	}

	@Override
	public void onSocketReceiveDataSuccess(String receiveMsg) {

	}

	@Override
	public void onSocketError(String errorMsg) {

	}

	private static final int socketLogin = 0x999;
	private static final int socketClose = 0x998;

	/** Handler快捷 */
	protected void localSendMessage(int what, Object object) {
		new MyHandler(Looper.getMainLooper()).sendMessage(NormalUtils
				.getMessage(what, object));
	}

	/** Handler快捷 */
	protected void localSendEmptyMessage(int What) {
		new MyHandler(Looper.getMainLooper()).sendEmptyMessage(What);
	}

	class MyHandler extends Handler {
		public MyHandler(Looper looper) {
			super(looper);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case socketLogin:
				socketPresenter.sendSocketCommand(Constants.getSocketCommand(
						current_user.getUser().getUserName(), 0, 0, "00:00", 0,
						0, 0, current_user.getUser().getHeadimgurl()));
				break;
			case socketClose:
				socketPresenter.closeSocket();
				break;
			}
		}
	}

}
